package com.freewater.library.lending.dailysheet.infrastructure.dao;

import com.freewater.library.lending.dailysheet.model.DailyCheckedOutCount;
import jakarta.persistence.EntityManager;
import jakarta.persistence.Query;
import org.springframework.data.jpa.repository.support.SimpleJpaRepository;

public class DailyCheckedOutDao extends SimpleJpaRepository<DailyCheckedOutCount, Long> {

    private final EntityManager entityManager;

    public DailyCheckedOutDao(EntityManager entityManager) {
        super(DailyCheckedOutCount.class, entityManager);
        this.entityManager = entityManager;
    }

    public boolean existsByUnique(DailyCheckedOutCount.Unique unique) {
        String hql = "select count(*) from DailyCheckedOutCount t where t.isbn = :isbn and t.day = :day ";
        Query query = this.entityManager.createQuery(hql, Long.class);
        query.setParameter("isbn", unique.getIsbn());
        query.setParameter("day", unique.getDay());
        Long count = (Long) query.getSingleResult();
        return count != null && count > 0;
    }

    public int deltaCount(DailyCheckedOutCount.Unique unique, int deltaCount) {
        String hql = "update DailyCheckedOutCount t " +
                "set t.checkedOutCount = t.checkedOutCount + :deltaCount " +
                "where t.isbn = :isbn and t.day = :day ";
        Query query = this.entityManager.createQuery(hql);
        query.setParameter("isbn", unique.getIsbn());
        query.setParameter("day", unique.getDay());
        query.setParameter("deltaCount", deltaCount);
        return query.executeUpdate();
    }
}
